<?php


namespace App\Exception\Handler;

use App\Constants\ErrorCode;
use Hyperf\ExceptionHandler\ExceptionHandler;
use Hyperf\HttpMessage\Stream\SwooleStream;
use Hyperf\Validation\ValidationException;
use Psr\Http\Message\ResponseInterface;
use Throwable;

/**
 * 自定义验证器异常处理
 * Class ValidationExceptionHandler
 * @package App\Exception\Handler
 */
class ValidationExceptionHandler extends ExceptionHandler
{
    public function handle(Throwable $throwable, ResponseInterface $response)
    {
        $data = json_encode([
            'errCode' => ErrorCode::CHECK_FAIL,
            'errMsg' => $throwable->validator->errors()->first()
        ]);

        // 阻止异常冒泡
        $this->stopPropagation();
        return $response->withHeader('Content-Type', 'application/json')->withStatus(ErrorCode::CHECK_FAIL)->withBody(new SwooleStream($data));
    }

    public function isValid(Throwable $throwable): bool
    {
        return $throwable instanceof ValidationException;
    }
}
